package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.util.IdSequence;
import javafx.animation.Timeline;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuyp
 * @date 2021/01/30
 */
@Slf4j
@Service
public class PublishApiImpl implements PublishApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdSequence idSequence;

    @Override
    public PageResult<Publish> findRecommendPublishList(long userId, int page, int pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("publishId").ne(null);
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))
                .with(PageRequest.of(page-1, pagesize));

        List<RecommendQuanZi> quanZiList = mongoTemplate.find(query, RecommendQuanZi.class);
        long count = mongoTemplate.count(query, RecommendQuanZi.class);

        List<Publish> publishList = new ArrayList<>();
        for (RecommendQuanZi quanZi : quanZiList) {
            Publish publish = mongoTemplate.findById(quanZi.getPublishId(), Publish.class);
            publishList.add(publish);
        }

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, publishList);
    }

    @Override
    public String savePublish(Publish publish) {
        //1. 把publish数据保存到quanzi_publish表里
        publish.setId(ObjectId.get());
        publish.setPid(idSequence.getNextId("quanzi_publish"));
        publish.setCreated(System.currentTimeMillis());
        mongoTemplate.save(publish);
        log.info("保存动态数据：{}", publish);

        //2. 把动态记录保存到用户自己的相册表 quanzi_album_用户id
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());
        log.info("记录到相册表{}，数据:{}", "quanzi_album_" + publish.getUserId(), album);

        //3. 把动态记录保存到所有好友的时间线表 quanzi_time_line_好友id
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        for (Friend friend : friendList) {
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setUserId(publish.getUserId());
            timeLine.setPublishId(publish.getId());
            timeLine.setCreated(System.currentTimeMillis());

            mongoTemplate.save(timeLine, "quanzi_time_line_" + friend.getFriendId());
            log.info("记录到时间线表{}，数据：{}", "quanzi_time_line_" + friend.getFriendId(), timeLine);
        }

        return publish.getId().toHexString();
    }

    @Override
    public PageResult<Publish> findTimelinePublishList(long userId, int page, int pagesize) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));

        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long count = mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);

        List<Publish> publishList = new ArrayList<>();
        for (TimeLine timeLine : timeLineList) {
            Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
            publishList.add(publish);
        }

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, publishList);
    }

    //ctrl + i: 列出所有可以implements的方法
    @Override
    public PageResult<Publish> findAlbumPublishList(long userId, int page, int pagesize) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));

        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        long count = mongoTemplate.count(query, Album.class, "quanzi_album_" + userId);

        List<Publish> publishList = new ArrayList<>();
        for (Album album : albumList) {
            Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
            publishList.add(publish);
        }

        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, publishList);
    }

    @Override
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId), Publish.class);
    }

    @Override
    public PageResult<Publish> findPublishListByState(int page, int pagesize, Long uid, Integer state) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));

        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }

        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }

        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, publishList);
    }

    @Override
    public void updateState(Publish publish) {
        Query query = new Query(Criteria.where("id").is(publish.getId()));
        Update update = new Update().set("state", publish.getState());
        mongoTemplate.updateFirst(query, update, Publish.class);
    }

    @Override
    public List<Publish> findPublishByPids(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        return mongoTemplate.find(query, Publish.class);
    }
}
